package cn.dqy.gotanserver.handle;

import cn.dqy.gotanserver.dto.ChannelInfo;
import cn.dqy.gotanserver.config.ConfigClass;
import cn.dqy.gotanserver.dto.GoTanInet;
import cn.dqy.gotanserver.support.EmailSupport;
import cn.dqy.gotanserver.support.SmsSupport;
import cn.dqy.gotanserver.support.SupportHelper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.InetSocketAddress;
import java.util.Map;

public class InboundHandle extends SimpleChannelInboundHandler<GoTanInet> {

    SmsSupport smsSupport;

    SupportHelper supportHelper;

    EmailSupport emailSupport;

    Map<String ,ChannelInfo> channelMap;

    ConfigClass gotanConfig;

    static         Logger logger = LoggerFactory.getLogger(InboundHandle.class);

    public InboundHandle(SupportHelper supportHelper,
                         SmsSupport smsSupport,
                         EmailSupport emailSupport,
                         Map<String , ChannelInfo> channelMap,
                         ConfigClass gotanConfig){
        this.supportHelper=supportHelper;
        this.smsSupport=smsSupport;
        this.emailSupport=emailSupport;
        this.channelMap=channelMap;
        this.gotanConfig=gotanConfig;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GoTanInet msg) throws Exception {
        logger.info("data={}",msg);
        NioSocketChannel channel= (NioSocketChannel) ctx.channel();
        InetSocketAddress remoteAddress = channel.remoteAddress();

        supportHelper.save(msg,remoteAddress.getHostName()+":"+remoteAddress.getPort());
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        NioSocketChannel channel= (NioSocketChannel) ctx.channel();
        InetSocketAddress remoteAddress = channel.remoteAddress();
        logger.info("新的连接到来--ip={},port={}",remoteAddress.getHostName(),remoteAddress.getPort());
        String addrKey = channel.remoteAddress().getHostName() + ":" + channel.remoteAddress().getPort(); //机器唯一标识

        channelMap.put(addrKey ,new ChannelInfo(channel,null));
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        NioSocketChannel channel= (NioSocketChannel) ctx.channel();
        String clientAddr=channel.remoteAddress().getHostName()+":"+channel.remoteAddress().getPort();
        logger.info( "{}断开连接",clientAddr);
        channelMap.remove(clientAddr);
    }


}
